//
//  TRFamousViewController.m
//  WeiMiLan
//
//  Created by cong on 14-7-26.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRFamousViewController.h"
#import "TRMemuCell.h"
#import "PullCollectionView.h"

#import "TRTabBarViewController.h"
@interface TRFamousViewController ()<PullCollectionViewDelegate>
@property (strong, nonatomic) PullCollectionView *collectionView;
@property (nonatomic,assign) int pageNum;

@property(nonatomic,strong)NSMutableArray * chongfuIDs;

@property(nonatomic,assign)NSInteger oldNum;
@property(strong,nonatomic)NSString * CATEGORY;
@property(strong,nonatomic)NSMutableArray * idArray;
@property(strong,nonatomic)NSDictionary * pageDict;
@end

@implementation TRFamousViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)pullCollectionViewDidTriggerRefresh:(PullCollectionView *)pullCollectionView{
    [pullCollectionView endRefreshing];
    [self performSelector:@selector(reflushNow) withObject:nil afterDelay:2.];
}

-(void)reflushNow{
    [self.collectionView endRefreshing];
    [self.collectionView endLoadingMore];
}

- (void)pullCollectionViewDidTriggerLoadMore:(PullCollectionView*)pullCollectionView{
    
    [pullCollectionView endLoadingMore];
    
    [self updataMyData:[NSString stringWithFormat:@"%d",++self.pageNum]];
    [self performSelector:@selector(reflushNow) withObject:nil afterDelay:2.];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.CATEGORY=@"";
    self.chongfuIDs = [@[] mutableCopy];
    self.famousArray =[@[] mutableCopy];
    self.idArray=[@[] mutableCopy];
    
    CHTCollectionViewWaterfallLayout *layout = [[CHTCollectionViewWaterfallLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerHeight = 0;
    layout.footerHeight = 0;
//    layout.minimumColumnSpacing = 10;
//    layout.minimumInteritemSpacing = 10;
    layout.columnCount = 1;
    CGRect r = CGRectMake(0, 72, self.view.frame.size.width, self.view.frame.size.height);
    self.collectionView = [[PullCollectionView alloc] initWithFrame:r collectionViewLayout:layout];
    self.collectionView.pullDelegate = self;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.refreshFooterView.isend = YES;
    self.pageNum = 1;
    self.collectionView.pullBackgroundColor = [UIColor whiteColor];
    self.collectionView.pullTextColor = [UIColor blackColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"TRMemuCell" bundle:nil] forCellWithReuseIdentifier:@"TRMemuCell"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.clearsContextBeforeDrawing = YES;
    [self.view addSubview:self.collectionView];
    
    //加产品，加请求
    [QLMaskUtil showMaskLoadingWithView:self.collectionView];
    [self updataMyData:[NSString stringWithFormat:@"%d",self.pageNum]];
    [self initNavigation];
    [self initSeachButton];
}

-(void)updataMyData:(NSString *)num{
    
    NSDictionary *params;
    
    if ([NSString isBlankString:ApplicationDelegate.markString]) {
        
        params=@{
                 TYPE:[NSString stringWithFormat:@"%d",DirectoryGoods],
                 PAGE_NUM:num,
                 PRODUCT_TYPE_CREATE_DATE:DIR_ORDER_FIELD_CREATEDATE,
                 PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC,
                 BRANDID:self.famousID,
                 @"CATEGORY":self.CATEGORY,
                 @"userId" : ApplicationDelegate.currentUserId
                 };
        
    }else
    {
        
        params=@{
                 TYPE:@"1010",
                 PAGE_NUM:num,
                 BID:ApplicationDelegate.markString,
                 BRANDID:self.famousID,
                 PRODUCT_TYPE_ORDER_FIELD:DIR_ORDER_FIELD_CREATEDATE,
                 PRODUCT_TYPE_ORDER_DIRECTION:DIR_ORDER_DIRECTION_ASC,
                 @"CATEGORY":self.CATEGORY,
                 @"userId" : ApplicationDelegate.currentUserId
                 };
        
    }
    [ApplicationDelegate.webAPI getWebAPIWithParams:params andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.collectionView];
        NSString * message = responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
        
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            
            if ([num isEqualToString:@"1"]){
                self.famousArray=[NSMutableArray array];
            }
            self.pageDict = responseObject[@"PAGE_INFO"];
            
            NSString * msg = responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
            
            for (NSDictionary * idName in responseObject[@"PACKAGE_RSP"][@"PACKAGE"]) {
                if (![self.idArray containsObject:idName[@"ID"]]) {
                    [self.famousArray addObject:idName];
                    [self.idArray containsObject:idName[@"ID"]];
                }
            }
            
            if (self.famousArray.count==0) {
                MMProgressHUDShowSuccess(@"没发现符合条件的产品");
            }
            
            if (msg.length>2) {
                MMProgressHUDShowSuccess(msg);
            }else{
                
                
            }
            
            if ([num intValue] >= [self.pageDict[@"PAGES"] intValue]) {
                [SVProgressHUD showErrorWithStatus:@"已无更多"];
                self.collectionView.refreshFooterView.isend = YES;
            }else
            {
                self.collectionView.refreshFooterView.isend = NO;
            }
            [self.collectionView reloadData];
            [self.collectionView endLoadingMore];
            [self.collectionView endRefreshing];
        }else{
            [MMProgressHUD dismissWithError:message];
        }
        
    }];
    
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=self.title;
    [self.weChatNavigationBar .leftButton addTarget:self action:@selector(exit)  forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.titleLabel.top=20;
    [self.weChatNavigationBar.rightButton setHidden:NO];
        
    [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"rli(1)"] forState:0];
    
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(showDateVC) forControlEvents:UIControlEventTouchUpInside];
    // self.weChatNavigationBar.rightButton.center = self.weChatNavigationBar.center;
    self.weChatNavigationBar.rightButton.origin = CGPointMake(self.view.width - 32, self.weChatNavigationBar.rightButton.origin.y + 5);
    self.weChatNavigationBar.rightButton.width = 22;
    self.weChatNavigationBar.rightButton.height = 22;
    //
    //    _tb=[[TableViewWithBlock alloc] initWithFrame:CGRectMake(kUI_SCREEN_WIDTH-105, 70, 100, 136)];
    //
    //
    //    _tb.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"rli"]];
    //    _tb.layer.borderWidth=4.0f;
    //    _tb.layer.borderColor=[[UIColor blackColor] CGColor];
    //    _tb.delegate=self;
    //    [ApplicationDelegate.window addSubview:_tb];
    //    _tb.hidden=YES;

}
- (void)showDateVC {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    TRNewsGoodsViewController *TVC=[sb instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
    [self.navigationController pushViewController:TVC animated:YES];
}
#pragma mark-----隐藏男女视图
-(void)showTB
{
    NSLog(@"======");
    if (_tb.hidden==YES) {
        _tb.hidden=NO;
    }else
    {
        _tb.hidden=YES;
        
    }
}

#pragma mark------男女视图
-(void)initSeachButton
{
    //_isOpened=NO;
    [_tb initTableViewDataSourceAndDelegate:^(UITableView *tableView,NSInteger section){
        
        return (NSInteger)3;
        
    } setCellForIndexPathBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        SelectionCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SelectionCell"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"SelectionCell" owner:self options:nil]objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        
        cell.lb.backgroundColor=[UIColor clearColor];
        cell.img.backgroundColor=[UIColor clearColor];
        cell.backgroundColor=[UIColor clearColor];
        cell.contentView.backgroundColor=[UIColor clearColor];
        UIView *v=[[UIView alloc] init];
        v.backgroundColor=[UIColor clearColor];
        cell.selectedBackgroundView=v;
        
        return cell;
    } setDidSelectRowBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        switch (indexPath.row) {
            case 0:
            {
                
                TRNewsGoodsViewController *TVC=[self.storyboard instantiateViewControllerWithIdentifier:@"TRNewsGoodsViewController"];
                [self.navigationController pushViewController:TVC animated:YES];
            }
                break;
            case 1:
            {
                
                self.CATEGORY=@"1";
                
                [self updataMyData:@"1"];
            }
                break;
            case 2:
            {
                
                self.CATEGORY=@"0";
                
                [self updataMyData:@"1"];
            }
                break;
                
            default:
                break;
        }
        _tb.hidden=YES;
    }];
    
    [_tb.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [_tb.layer setBorderWidth:2];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.collectionView.height=kUI_SCREEN_HEIGHT-64-44;
    
}

-(void)exit
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    self.oldNum =self.famousArray.count;
    
    return self.famousArray.count;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TRMemuCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"TRMemuCell" forIndexPath:indexPath];
    cell.backgroundColor=[UIColor grayColor];
    cell.info = self.famousArray[indexPath.row];
 //   cell.selectImageView.hidden = YES;
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TRProductDetailViewController *vc = [[TRProductDetailViewController alloc] init];
    vc.productTypeId = self.famousArray[indexPath.row][@"ID"];
    [self presentViewController:vc animated:YES completion:nil];
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSArray * goods = self.famousArray;
    TRMemuCell *cell =[[TRMemuCell alloc] init];
    cell.info = [goods objectAtIndex:indexPath.row];
    return [cell getSize];
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 2;
}

@end
